package filestore

import (
	"app-box/api_error"
	"app-box/config"
	"app-box/tools"
	"os"
	"path/filepath"
)

type LocalFileStore struct {
}

func localFilePathForKey(key string) string {
	return filepath.Join(config.LocalFile.FilaSavePath, key)
}

func (store *LocalFileStore) Copy(fromKey, toKey string) {
	fromPath := localFilePathForKey(fromKey)
	toPath := localFilePathForKey(toKey)
	if _, err := tools.CopyFile(fromPath, toPath); err != nil {
		panic(api_error.IOError(err))
	}
}

func (store *LocalFileStore) Delete(Keys ...string) {
	for _, key := range Keys {
		filePath := localFilePathForKey(key)
		if err := os.Remove(filePath); err != nil {
			panic(api_error.IOError(err))
		}
	}
}

func (store *LocalFileStore) UploadString(str string, key string) (url FileString) {
	tools.SaveDataTo([]byte(str), localFilePathForKey(key))
	return FileKey{ObjectKey: key, Type: FileKeyTypeLocal}.ToFileStr()
}

var localStore = LocalFileStore{}
